package com.zly.entity;

import com.zly.entity.enums.PlaceholderType;

import java.util.regex.Pattern;

public class Placeholder {

    private final static Pattern LEGAL_PLACEHOLDER_PATTERN;//placeholder字符串的合法模式

    //初始化LEGAL_PLACEHOLDER_PATTERN
    static {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(");
        for(PlaceholderType placeholderType : PlaceholderType.values()) {
            String symbolString = placeholderType.getSymbolString();
            if(symbolString.equals("$")) {
                symbolString = "\\$";
            }
            stringBuilder.append(symbolString).append("|");
        }
        stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), ")");
        stringBuilder.append("\\{\\w+\\}");

        LEGAL_PLACEHOLDER_PATTERN = Pattern.compile(stringBuilder.toString());

    }

    private final PlaceholderType type;
    private final String name;

    //获取placeholder字符串的合法模式
    public static Pattern getLegalPattern() {
        return LEGAL_PLACEHOLDER_PATTERN;
    }

    //构造
    public Placeholder(PlaceholderType type, String name) {
        this.type = type;
        this.name = name;
    }

    public Placeholder(String placeholderString) {


        if (!LEGAL_PLACEHOLDER_PATTERN.matcher(placeholderString).matches()) {//若placeholderString字符串格式不合法
            throw new IllegalArgumentException("Placeholder字符串不合法:" + placeholderString);
        }

        int leftCurlyBraceIndex = placeholderString.indexOf('{');
        int rightCurlyBraceIndex = placeholderString.indexOf('}');
        this.type = PlaceholderType.fromSymbol(placeholderString.substring(0, leftCurlyBraceIndex));
        this.name = placeholderString.substring(leftCurlyBraceIndex + 1, rightCurlyBraceIndex);

    }

    @Override
    public String toString() {
        return type.getSymbolString()+"{"+name+"}";
    }

    //getter
    public PlaceholderType getType() {
        return type;
    }

    public String getName() {return name;}

}
